package com.hanserwei.han_picture.service.seviceImpl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hanserwei.han_picture.domain.entity.po.Space;
import com.hanserwei.han_picture.domain.entity.po.SpaceUser;
import com.hanserwei.han_picture.domain.entity.po.User;
import com.hanserwei.han_picture.domain.entity.vo.SpaceVO;
import com.hanserwei.han_picture.domain.entity.vo.UserVO;
import com.hanserwei.han_picture.domain.exception.ApiException;
import com.hanserwei.han_picture.domain.request.space.SpaceAddRequest;
import com.hanserwei.han_picture.domain.request.space.SpaceEditRequest;
import com.hanserwei.han_picture.domain.request.space.SpaceQueryRequest;
import com.hanserwei.han_picture.domain.request.space.SpaceUpdateRequest;
import com.hanserwei.han_picture.enums.ResponseCodeEnum;
import com.hanserwei.han_picture.enums.SpaceLevelEnum;
import com.hanserwei.han_picture.enums.SpaceTypeEnum;
import com.hanserwei.han_picture.enums.SpaceUserRoleEnum;
import com.hanserwei.han_picture.mapper.SpaceMapper;
import com.hanserwei.han_picture.service.SpaceService;
import com.hanserwei.han_picture.service.SpaceUserService;
import com.hanserwei.han_picture.service.UserService;
import com.hanserwei.han_picture.utils.ThrowUtils;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class SpaceServiceImpl extends ServiceImpl<SpaceMapper, Space> implements SpaceService {


    private final UserService userService;
    private final TransactionTemplate transactionTemplate;
    private final SpaceUserService spaceUserService;

    /**
     * 分页获取空间列表(未脱敏)
     *
     * @param request 查询参数
     * @return 分页数据
     */
    @Override
    public Page<Space> listSpaceByPage(@NotNull SpaceQueryRequest request) {
        int current = request.getCurrent();
        int pageSize = request.getPageSize();
        Page<Space> spacePage = new Page<>(current, pageSize);
        QueryWrapper<Space> queryWrapper = getQueryWrapper(request);
        return this.page(spacePage, queryWrapper);
    }

    /**
     * 分页获取空间的 VO (处理 UserVO)
     *
     * @param spacePage 空间的分页数据
     * @return 空间的 VO
     */
    @Override
    public Page<SpaceVO> getSpaceVOPage(@NotNull Page<Space> spacePage) {
        List<Space> spaceList = spacePage.getRecords();
        // 构造 Page<SpaceVO>
        Page<SpaceVO> spaceVOPage = new Page<>(spacePage.getCurrent(), spacePage.getSize(), spacePage.getTotal());
        if (CollUtil.isEmpty(spaceList)) {
            return spaceVOPage;
        }
        // 获取 List<SpaceVO>
        List<SpaceVO> spaceVOList = spaceList.stream()
                .map(this::getSpaceVO)
                .collect(Collectors.toList());
        // 关联查询用户信息
        // 1. 获取用户 id 集合
        Set<Long> userIdSet = spaceList.stream()
                .map(Space::getUserId)
                .collect(Collectors.toSet());
        // 2. 获取用户集合
        List<User> userList = userService.listByIds(userIdSet);
        // 3. (userId, User) 进行分组
        Map<Long, List<User>> userMap = userList.stream()
                .collect(Collectors.groupingBy(User::getId));
        // 4. 遍历填充数据
        spaceVOList.forEach(spaceVO -> {
            Long userId = spaceVO.getUserId();
            User user = null;
            if (userMap.containsKey(userId)) {
                user = userMap.get(userId).getFirst();
            }
            spaceVO.setUser(userService.getUserVO(user));
        });
        spaceVOPage.setRecords(spaceVOList);
        return spaceVOPage;
    }

    /**
     * 获取空间的 VO(处理 UserVO)
     *
     * @param space 空间
     * @return 图片的 VO
     */
    @Override
    public SpaceVO getSpaceVO(Space space) {
        ThrowUtils.throwIf(space == null, ResponseCodeEnum.RESOURCE_NOT_FOUND, "空间不存在");
        // 1. 获取 SpaceVO
        SpaceVO spaceVO = this.spaceToSpaceVO(space);
        // 2. 关联查询
        Long userId = spaceVO.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            UserVO userVO = userService.getUserVO(user);
            spaceVO.setUser(userVO);
        }
        return spaceVO;
    }


    /**
     * 校验空间权限
     *
     * @param loginUser 登录用户
     * @param space     空间
     */
    @Override
    public void checkSpaceAuth(@NotNull User loginUser, @NotNull Space space) {
        // 仅本人或管理员可编辑
        Space seletedSpace = this.getById(space.getId());
        if (!seletedSpace.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new ApiException(ResponseCodeEnum.UNAUTHORIZED, "权限不足");
        }
    }

    /**
     * Space 转 SpaceVO
     *
     * @param space Space
     * @return SpaceVO
     */
    @Override
    public SpaceVO spaceToSpaceVO(Space space) {
        if (ObjUtil.isNull(space)) {
            return null;
        }
        SpaceVO spaceVO = new SpaceVO();
        BeanUtil.copyProperties(space, spaceVO);
        return spaceVO;
    }

    /**
     * SpaceVO 转 Space
     *
     * @param spaceVO SpaceVO
     * @return Space
     */
    @Override
    public Space spaceVOtoSpace(SpaceVO spaceVO) {
        if (ObjUtil.isNull(spaceVO)) {
            return null;
        }
        Space space = new Space();
        BeanUtil.copyProperties(spaceVO, space);
        return space;
    }

    /**
     * 封装空间分页查询条件
     *
     * @param queryRequest 查询字段
     * @return 查询条件
     */
    @Override
    public QueryWrapper<Space> getQueryWrapper(SpaceQueryRequest queryRequest) {
        QueryWrapper<Space> wrapper = new QueryWrapper<>();
        // 1. 为空直接返回
        if (queryRequest == null) {
            return wrapper;
        }
        // 2. 取出所有字段
        Long id = queryRequest.getId();
        Long userId = queryRequest.getUserId();
        String spaceName = queryRequest.getSpaceName();
        Integer spaceLevel = queryRequest.getSpaceLevel();
        Integer spaceType = queryRequest.getSpaceType();
        String sortField = queryRequest.getSortField();
        String sortOrder = queryRequest.getSortOrder();
        // 3. 封装查询条件
        wrapper.eq(id != null && id > 0, "id", id);
        wrapper.eq(userId != null && userId > 0, "user_id", userId);
        wrapper.like(StrUtil.isNotBlank(spaceName), "space_name", spaceName);
        wrapper.eq(spaceLevel != null && (spaceLevel == 0 || spaceLevel == 1 || spaceLevel == 2), "space_level", spaceLevel);
        wrapper.eq(spaceType != null && (spaceType == 0 || spaceType == 1), "space_type", spaceType);
        // 4. 排序
        wrapper.orderBy(StrUtil.isNotBlank(sortField), sortOrder.equals("ascend"), sortField);
        // 5. 返回结果
        return wrapper;
    }

    /**
     * 删除空间
     *
     * @param id        空间 id
     * @param loginUser 登录用户
     * @return 是否删除成功
     */
    @Override
    public boolean deleteSpace(Long id, User loginUser) {
        Space space = this.getById(id);
        ThrowUtils.throwIf(space == null, ResponseCodeEnum.RESOURCE_NOT_FOUND, "空间不存在");
        // 仅本人或管理员可删除
        this.checkSpaceAuth(loginUser, space);
        boolean result = this.removeById(id);
        ThrowUtils.throwIf(!result, ResponseCodeEnum.SYSTEM_ERROR, "删除空间失败");
        return true;
    }

    /**
     * 校验空间参数
     *
     * @param space 空间
     * @param add   是否是新添加空间
     */
    @Override
    public void validSpace(Space space, boolean add) {
        ThrowUtils.throwIf(space == null, ResponseCodeEnum.INVALID_PARAMETER, "参数错误！");
        String spaceName = space.getSpaceName();
        Integer spaceLevel = space.getSpaceLevel();
        Integer spaceType = space.getSpaceType();
        SpaceLevelEnum spaceLevelEnum = SpaceLevelEnum.getEnumByValue(spaceLevel);
        SpaceTypeEnum spaceTypeEnum = SpaceTypeEnum.getEnumByValue(spaceType);
        // 创建空间
        if (BooleanUtil.isTrue(add)) {
            ThrowUtils.throwIf(StrUtil.isBlank(spaceName), ResponseCodeEnum.INVALID_PARAMETER, "空间名称不能为空！");
            ThrowUtils.throwIf(spaceLevelEnum == null, ResponseCodeEnum.INVALID_PARAMETER, "空间级别错误！");
            ThrowUtils.throwIf(spaceTypeEnum == null, ResponseCodeEnum.INVALID_PARAMETER, "空间类型错误！");
        } else {
            // 更新空间
            // 空间名称不超过30 字
            ThrowUtils.throwIf(StrUtil.isNotBlank(spaceName) && spaceName.length() > 30, ResponseCodeEnum.INVALID_PARAMETER, "空间名称过长！");
            ThrowUtils.throwIf(spaceLevel != null && spaceLevelEnum == null, ResponseCodeEnum.INVALID_PARAMETER, "空间级别错误！");
            ThrowUtils.throwIf(spaceType != null && spaceTypeEnum == null, ResponseCodeEnum.INVALID_PARAMETER, "空间类型错误！");
        }
    }

    /**
     * 编辑空间
     *
     * @param editRequest 编辑空间请求
     * @param loginUser   登录用户
     * @return 是否编辑成功
     */
    @Override
    public boolean editSpace(SpaceEditRequest editRequest, User loginUser) {
        Space space = new Space();
        BeanUtil.copyProperties(editRequest, space);
        // 数据校验
        validSpace(space, false);
        // 仅本人可编辑
        this.checkSpaceAuth(loginUser, space);
        // 填充数据
        fillSpaceBySpaceLevel(space);
        space.setEditTime(LocalDateTime.now());
        // 查询空间是否存在
        Space oldSpace = this.getById(space.getId());
        ThrowUtils.throwIf(oldSpace == null, ResponseCodeEnum.RESOURCE_NOT_FOUND, "空间不存在！");
        boolean result = this.updateById(space);
        ThrowUtils.throwIf(!result, ResponseCodeEnum.SYSTEM_ERROR, "更新空间失败！");
        return true;
    }

    /**
     * 更新空间(使用锁和事务确保一个用户只有一个空间)
     *
     * @param request 更新空间请求
     * @return 是否更新成功
     */
    @Override
    public long addSpace(SpaceAddRequest request, User loginUser) {
        ThrowUtils.throwIf(request == null, ResponseCodeEnum.INVALID_PARAMETER, "参数错误！");
        ThrowUtils.throwIf(loginUser == null, ResponseCodeEnum.INVALID_PARAMETER, "用户未登录或不存在！");
        Space space = new Space();
        BeanUtil.copyProperties(request, space);
        // 校验参数
        if (StrUtil.isBlank(space.getSpaceName())) {
            space.setSpaceName("未命名空间");
        }
        if (space.getSpaceLevel() == null) {
            space.setSpaceLevel(SpaceLevelEnum.COMMON.getValue());
        }
        if (space.getSpaceType() == null) {
            space.setSpaceType(SpaceTypeEnum.PRIVATE.getValue());
        }
        // 填充数据
        fillSpaceBySpaceLevel(space);
        validSpace(space, true);
        space.setUserId(loginUser.getId());
        ThrowUtils.throwIf(!SpaceLevelEnum.COMMON.getValue().equals(space.getSpaceLevel()) && !userService.isAdmin(loginUser), ResponseCodeEnum.UNAUTHORIZED, "非管理员不能创建非普通空间！");
        // 控制一个用户只可以创建一个私人空间,以及一个团队空间
        final String LOCK = String.valueOf(loginUser.getId()).intern();
        synchronized (LOCK) {
            transactionTemplate.execute(status -> {
                // 判断是否创建过
                if (!userService.isAdmin(loginUser)) {
                    boolean exists = this.lambdaQuery()
                            .eq(Space::getUserId, loginUser.getId())
                            .eq(Space::getSpaceType, space.getSpaceType())
                            .exists();
                    if (exists) {
                        throw new ApiException(ResponseCodeEnum.SYSTEM_ERROR, "每个用户每类空间仅能创建一个");
                    }
                }
                boolean saved = this.save(space);
                ThrowUtils.throwIf(!saved, ResponseCodeEnum.SYSTEM_ERROR, "创建空间失败！");
                // 如果是团队空间, 就需要新增一个团队空间用户(自己也算是团队空间的一员, 并且空间创建人就是空间管理员)
                if (ObjUtil.equals(SpaceTypeEnum.TEAM.getValue(), request.getSpaceType())) {
                    SpaceUser spaceUser = SpaceUser.builder()
                            .spaceId(space.getId())
                            .userId(loginUser.getId())
                            .spaceRole(SpaceUserRoleEnum.ADMIN.getValue())
                            .build();
                    boolean result = spaceUserService.save(spaceUser);
                    ThrowUtils.throwIf(!result, ResponseCodeEnum.SYSTEM_ERROR, "创建团队空间成员失败");
                }
                return space.getId();
            });
            return Optional.ofNullable(space.getId()).orElse(-1L);
        }
    }

    /**
     * 更新空间（管理员用）
     *
     * @param request 更新空间请求
     * @return 是否更新成功
     */
    @Override
    public boolean updateSpace(SpaceUpdateRequest request) {
        Space space = new Space();
        BeanUtil.copyProperties(request, space);
        // 自动填充空间级别数据
        fillSpaceBySpaceLevel(space);
        // 校验参数
        validSpace(space, false);
        // 判断空间是否存在
        Space oldSpace = this.getById(space.getId());
        ThrowUtils.throwIf(oldSpace == null, ResponseCodeEnum.RESOURCE_NOT_FOUND, "空间不存在！");
        // 执行更新
        boolean result = this.updateById(space);
        ThrowUtils.throwIf(!result, ResponseCodeEnum.SYSTEM_ERROR, "更新空间失败！");
        return true;
    }

    /**
     * 根据空间级别设置空间最大大小和最大数量
     *
     * @param space 空间
     */
    public void fillSpaceBySpaceLevel(Space space) {
        ThrowUtils.throwIf(space == null, ResponseCodeEnum.INVALID_PARAMETER, "参数错误！");
        Integer spaceLevel = space.getSpaceLevel();
        SpaceLevelEnum spaceLevelEnum = SpaceLevelEnum.getEnumByValue(spaceLevel);
        if (spaceLevelEnum != null) {
            long maxSize = spaceLevelEnum.getMaxSize();
            if (space.getMaxSize() == null) {
                space.setMaxSize(maxSize);
            }
            long maxCount = spaceLevelEnum.getMaxCount();
            if (space.getMaxCount() == null) {
                space.setMaxCount(maxCount);
            }
        }
    }

    /**
     * 验证空间配额是否足够
     *
     * @param spaceId         空间ID
     * @param additionalCount 要添加的图片数量
     * @param additionalSize  要添加的图片总大小
     * @return 是否有足够配额
     */
    @Override
    public boolean checkSpaceQuota(Long spaceId, long additionalCount, long additionalSize) {
        if (spaceId == null) {
            return true; // 公共空间不限制配额
        }

        Space space = this.getById(spaceId);
        if (space == null) {
            return false;
        }

        // 检查数量配额
        long currentCount = space.getTotalCount() != null ? space.getTotalCount() : 0L;
        long maxCount = space.getMaxCount() != null ? space.getMaxCount() : 0L;
        if (currentCount + additionalCount > maxCount) {
            return false;
        }

        // 检查大小配额
        long currentSize = space.getTotalSize() != null ? space.getTotalSize() : 0L;
        long maxSize = space.getMaxSize() != null ? space.getMaxSize() : 0L;
        return currentSize + additionalSize <= maxSize;
    }

    /**
     * 获取空间剩余配额信息
     *
     * @param spaceId 空间ID
     * @return 包含剩余配额的数组 [剩余数量, 剩余大小]
     */
    @Override
    public long[] getSpaceRemainingQuota(Long spaceId) {
        if (spaceId == null) {
            return new long[]{Long.MAX_VALUE, Long.MAX_VALUE}; // 公共空间不限制
        }

        Space space = this.getById(spaceId);
        if (space == null) {
            return new long[]{0L, 0L};
        }

        long currentCount = space.getTotalCount() != null ? space.getTotalCount() : 0L;
        long maxCount = space.getMaxCount() != null ? space.getMaxCount() : 0L;
        long remainingCount = Math.max(0L, maxCount - currentCount);

        long currentSize = space.getTotalSize() != null ? space.getTotalSize() : 0L;
        long maxSize = space.getMaxSize() != null ? space.getMaxSize() : 0L;
        long remainingSize = Math.max(0L, maxSize - currentSize);

        return new long[]{remainingCount, remainingSize};
    }
}
